<template>
  <div class="app-container">
    <el-form
      label-position="top"
      v-show="state.showSearch"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
    >
      <el-form-item label="公司名称" prop="companyId">
        <ApiSelect
          v-model="queryParams.companyId"
          :api="selectState.company.api"
          :params="selectState.company.params"
          :valueField="selectState.company.valueField"
          :labelField="selectState.company.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        <ApiSelect
          :params="{ companyId: queryParams.companyId }"
          v-model="queryParams.areaId"
          :api="selectState.area.api"
          :valueField="selectState.area.valueField"
          :labelField="selectState.area.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="线路名称" prop="routeId">
        <ApiSelect
          :params="{ areaId: queryParams.areaId }"
          v-model="queryParams.routeId"
          :api="selectState.route.api"
          :valueField="selectState.route.valueField"
          :labelField="selectState.route.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="点位名称" prop="positionName">
        <el-input v-model="queryParams.positionName" placeholder="点位名称" />
      </el-form-item>
      <el-form-item label="点位类型" prop="typeName">
        <ApiSelect
          v-model="queryParams.typeName"
          :api="selectState.type.api"
          :checkParams="false"
          :valueField="selectState.type.valueField"
          :labelField="selectState.type.labelField"
        />
      </el-form-item>
      <el-form-item label="点位标签" prop="label">
        <el-select v-model="queryParams.label" placeholder="请选择">
          <el-option label="特殊点位" :value="1" />
          <el-option label="普通点位" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select v-model="queryParams.enable" placeholder="请选择" clearable>
          <el-option
            v-for="dict in sys_common_staus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['tissue:position:add']" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList">
      <el-table-column type="selection" width="50" />
      <el-table-column label="公司名称" align="center" prop="companyName" min-width="120" />
      <el-table-column label="区域名称" align="center" prop="areaName" />
      <el-table-column label="线路名称" align="center" prop="routeName" />
      <el-table-column label="点位名称" align="center" prop="positionName" />
      <el-table-column label="点位类型" align="center" prop="positionTypeName" />
      <el-table-column label="点位标签" align="center" prop="label">
        <template #default="{ row }">
          <span>{{ row.label === 1 ? '特殊点位' : '普通点位' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备数量" align="center" prop="machineCount" width="80" />
      <el-table-column label="在线数量" align="center" prop="onlineCount" width="80" />
      <el-table-column label="离线数量" align="center" prop="noCount" width="80" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="{ row }">
          <dict-tag :options="sys_common_staus" :value="row.enable" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" fixed="right" width="150">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleTableAction(row, 'detail')">查看</el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['tissue:position:edit']"
            @click="handleTableAction(row, 'edit')"
            >编辑</el-button
          >
          <ConfirmButton
            v-hasPermi="['tissue:position:dis']"
            :row="row"
            tipText="此点位"
            @confirm="handleTableAction"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog v-model="state.visible" :close-on-click-modal="false" destroy-on-close>
      <AreaDetail
        v-if="state.actionType == 'detail'"
        @close="state.visible = false"
        :positionId="state.detailId"
      />
      <template v-else>
        <el-form
          ref="dialogFormRef"
          :model="dialogFormModel"
          :rules="state.formRules"
          label-position="top"
          :inline="true"
        >
          <el-form-item label="公司名称" prop="companyId">
            <ApiSelect
              :params="selectState.company.enableParams"
              v-model="dialogFormModel.companyId"
              :api="selectState.company.api"
              :valueField="selectState.company.valueField"
              :labelField="selectState.company.labelField"
              :immediate="isEdit"
            />
          </el-form-item>
          <el-form-item label="区域名称" prop="areaId">
            <ApiSelect
              :params="{ companyId: dialogFormModel.companyId, enable: 1 }"
              v-model="dialogFormModel.areaId"
              :api="selectState.area.api"
              :valueField="selectState.area.valueField"
              :labelField="selectState.area.labelField"
              :immediate="isEdit"
              @change="onAreaChange"
            />
          </el-form-item>
          <el-form-item label="线路名称" prop="routeId">
            <ApiSelect
              :params="{ areaId: dialogFormModel.areaId, enable: 1, cityName: cityName }"
              v-model="dialogFormModel.routeId"
              :api="selectState.route.api"
              :valueField="selectState.route.valueField"
              :labelField="selectState.route.labelField"
              :immediate="isEdit"
              clearable
            />
          </el-form-item>
          <el-form-item label="点位类型" prop="positionTypeId">
            <ApiSelect
              :params="{ enable: 1, routeId: dialogFormModel.routeId, cityName: cityName }"
              v-model="dialogFormModel.positionTypeId"
              :api="selectState.type.api"
              :valueField="selectState.type.valueField"
              :labelField="selectState.type.labelField"
              :immediate="isEdit"
              clearable
            />
          </el-form-item>
          <el-form-item label="点位名称" prop="positionName">
            <el-input placeholder="请输入" v-model="dialogFormModel.positionName" />
          </el-form-item>
          <el-form-item label="点位对接人" prop="contracts">
            <el-input placeholder="请输入" v-model="dialogFormModel.contracts" />
          </el-form-item>
          <el-form-item label="联系方式" prop="mobile">
            <el-input placeholder="请输入" v-model="dialogFormModel.mobile" />
          </el-form-item>
          <el-form-item label="客服人员" prop="operationUserId">
            <ApiSelect
              :params="{
                type: 'positionCustomer',
                enable: 1,
                companyId: dialogFormModel.companyId,
                cityName: cityName
              }"
              v-model="dialogFormModel.operationUserId"
              :api="selectState.user.api"
              :valueField="selectState.user.valueField"
              :labelField="selectState.user.labelField"
              :immediate="isEdit"
              clearable
            />
          </el-form-item>

          <el-form-item
            v-hasPermi="['tissue:position:all']"
            label="分账方（特约商户）"
            prop="investorUserId"
          >
            <el-select
              v-model="dialogFormModel.investorUserId"
              class="m-2"
              placeholder="请选择"
              size="default"
              @visible-change="visible_change"
              @change="change"
              :filterable="true"
            >
              <el-option
                v-for="item in specialMerchantOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-hasPermi="['tissue:position:all']"
            label="收款账号"
            prop="proceedsAccount"
          >
            <el-input
              v-model.trim="dialogFormModel.proceedsAccount"
              placeholder="请输入"
              type="number"
            />
          </el-form-item>
          <el-form-item v-hasPermi="['tissue:position:all']" label="交易手续费" prop="feeRate">
            <el-input
              v-model.trim="dialogFormModel.feeRate"
              placeholder="请输入"
              @blur="blur(dialogFormModel.feeRate)"
              @focus="focus(dialogFormModel)"
            />
          </el-form-item>
          <el-form-item
            v-hasPermi="['tissue:position:all']"
            label="点位总分账比例"
            prop="proportion"
          >
            <el-select
              v-model="dialogFormModel.proportion"
              class="m-2"
              placeholder="请选择"
              size="default"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <div v-hasPermi="['tissue:position:all']" style="height: 30px; line-height: 30px"
          >创客（分账接收方）</div
        >
        <el-table
          v-hasPermi="['tissue:position:all']"
          v-loading="state.loading"
          :data="dialogFormModel.positionSharings"
        >
          <el-table-column label="类型" align="center" prop="type" min-width="120">
            <template #default="{ row }">
              <el-select
                v-model="row.type"
                @change="typeChange(row)"
                placeholder="请选择"
                size="default"
                :filterable="true"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="收款方名字+账号" align="center" prop="userId" min-width="150">
            <template #default="{ row }">
              <el-select
                v-if="row.type === 4"
                v-model="row.userId"
                placeholder="请选择"
                size="default"
                :filterable="true"
                @change="(val, option) => getChange(row, val, option)"
              >
                <el-option
                  v-for="item in serviceProvidersOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <ApiSelect
                v-else-if="row.type === 1 || row.type === 2"
                :params="{
                  roleId: row.type === 1 ? '21' : row.type === 2 ? '19' : ''
                }"
                v-model="row.userId"
                :api="selectState.allocatedUser.api"
                :resultField="selectState.allocatedUser.resultField"
                :valueField="'userId'"
                :labelField="'nickName'"
                :immediate="isEdit"
                clearable
              />
              <ApiSelect
                v-else
                :params="{ roleId: '20' }"
                v-model="row.userId"
                :api="selectState.allocatedUser.api"
                :resultField="selectState.allocatedUser.resultField"
                :valueField="'userId'"
                :labelField="'nickName'"
                :immediate="isEdit"
                @change="(val, option) => getChange(row, val, option)"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="收款账号" align="center" prop="accountNumber" width="200">
            <template #default="{ row }">
              <el-input
                v-if="row.type === 3 || row.type === 4"
                v-model.trim="row.accountNumber"
                :placeholder="row.type === 3 ? '用户列表手机号' : '商户编号'"
                :disabled="row.type === 3 || row.type === 4 ? true : false"
              />
              <el-input v-else v-model.trim="row.accountNumber" placeholder="商户编号" />
            </template>
          </el-table-column>
          <el-table-column label="结算周期" align="center" prop="freezeDay">
            <template #default="{ row }">
              <el-select
                v-model="row.freezeDay"
                placeholder="请选择"
                size="default"
                :filterable="true"
              >
                <el-option
                  v-for="item in freezeDayOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="分账比例" align="center" prop="proportion">
            <template #default="{ row }">
              <el-input
                v-model.trim="row.proportion"
                @blur="validateProportion(row)"
                @focus="focusProportion(row)"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="&nbsp;" align="center" fixed="right" width="100">
            <template #default="scope">
              <el-button @click="procList('delete', scope.$index)"
                ><el-icon><Remove /></el-icon
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-hasPermi="['tissue:position:all']" style="display: flex; justify-content: center">
          <el-button icon="Plus" @click="procList('add')"> 添加 </el-button>
        </div>
      </template>

      <template v-if="state.actionType != 'detail'" #footer>
        <el-button @click="handleAction(false)">取消</el-button>
        <el-button type="primary" @click="handleAction(true)">
          {{ state.actionType == 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Area">
import { ElMessage } from 'element-plus'
import {
  getPositionList,
  updatePosition,
  addPosition,
  disablePoint
} from '@/api/organization/points'
import { formRules } from '@/utils/valid/formRules'
import AreaDetail from '../components/areaDetail.vue'
import { useOrganApiConfig } from '@/hooks/service'
import { onMountedOrActivated } from '@/hooks/common'
import { handleUpdConfirm, handleAreaName } from '@/utils/tools'
import { getRoleApi } from '@/api/organization/common'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const isAllPermissions = computed(() =>
  userStore.permissions.some((i) => i === 'tissue:position:all' || i === '*:*:*')
)

const selectState = useOrganApiConfig()
const queryRef = ref(null)
const dialogFormRef = ref(null)
const { proxy } = getCurrentInstance()
const { sys_common_staus } = proxy.useDict('sys_common_staus')

const tableList = ref([])
const cityName = ref('')
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const options = Array.from({ length: 31 }, (_, index) => ({
  label: `${index}%`,
  value: index
}))
const typeOptions = [
  {
    label: `创客-特约商户`,
    value: 1
  },
  {
    label: `创客-普通商户`,
    value: 2
  },
  {
    label: `创客-个人`,
    value: 3
  },
  {
    label: `创客-服务商`,
    value: 4
  }
]

const serviceProvidersOptions = [
  {
    label: `八九食服务商`,
    value: -1,
    dictValue: '1659657448'
  }
]
const freezeDayOptions = ref([])
const dialogFormModel = ref({
  positionId: '',
  companyId: '',
  areaId: '',
  routeId: '',
  contracts: '',
  mobile: '',
  positionName: '',
  positionTypeId: '',
  proportion: '',
  feeRate: '',
  proceedsAccount: '',
  operationUserId: '',
  investorUserId: '',
  positionSharings: [
    {
      type: 3,
      userId: '',
      openId: '',
      accountNumber: '',
      freezeDay: '',
      proportion: ''
    }
  ]
})
const state = reactive({
  visible: false,
  actionType: '',
  showSearch: true,
  total: 0,
  loading: false,
  operType: '',
  formRules: {
    companyId: formRules.set('请选择', 'change'),
    areaId: formRules.set('请选择', 'change'),
    routeId: formRules.set('请选择', 'change'),
    positionTypeId: formRules.set('请选择', 'change'),
    positionName: formRules.set('请输入点位名称', 'change'),
    contracts: formRules.singleMaxStr,
    mobile: formRules.singleContact,
    operationUserId: formRules.set('请选择', 'change')
  },
  bottomRules: {},
  detailId: ''
})

const isEdit = computed(() => state.actionType == 'edit')
function handleSearch(confirm) {
  !confirm && queryRef.value.resetFields()
  queryParams.value.pageNum = 1
  getList(true)
}

async function getList() {
  state.loading = true

  try {
    const r = await getPositionList(queryParams.value)
    tableList.value = r?.data ?? r?.rows
    state.total = r.total
  } finally {
    state.loading = false
  }
}
/** 单独处理 交易手续费不能小于 0.6% */
function blur() {
  let feeRate = Number(dialogFormModel.value.feeRate)
  if (isNaN(feeRate)) {
    dialogFormModel.value.feeRate = 0.6 + '%'
    return ElMessage.warning('请输入数字')
  }
  if (feeRate < 0.6 || feeRate > 1.0) {
    dialogFormModel.value.feeRate = 0.6
    ElMessage.warning('此数据输入范围 0.60~1.00')
  } else if (feeRate < 0) {
    dialogFormModel.value.feeRate = 0.6
    ElMessage.warning('比例不能为负数！')
  }
  dialogFormModel.value.feeRate = `${Math.max(0.6, Math.min(1.0, feeRate))}%`
}
function focus(row) {
  if (row.feeRate) {
    row.feeRate = parseFloat(row.feeRate.replace('%', ''))
  }
}

/** 限制比例不能输入负数，并且不能是非数字的值 */
function validateProportion(row) {
  let proportion = Number(row.proportion)

  if (isNaN(proportion)) {
    ElMessage.warning('请输入数字')
    proportion = 0
  } else if (proportion < 0) {
    ElMessage.warning('比例不能为负数！')
    proportion = 0
  }
  row.proportion = `${Math.max(0, proportion)}%`
}
function focusProportion(row) {
  if (row.proportion) {
    row.proportion = parseFloat(row.proportion.replace('%', ''))
  }
}

/** 类型切换的时候，清空后面的数据 */
function typeChange(row) {
  row.openId = ''
  row.userId = ''
  row.accountNumber = ''
  row.freezeDay = ''
  row.proportion = ''
}
const specialMerchantOptions = ref([])
/** 单独处理这条数据  */
function visible_change(visible) {
  if (visible && specialMerchantOptions.value.length <= 0) {
    getRolelist()
  }
}
function onAreaChange(ev, item) {
  console.log({ item })
  cityName.value = item.name ? item.name.split('/')[0] : ''

  console.log(cityName.value)
}
/** 获取服务商 */
function getRolelist() {
  getRoleApi({ roleId: 18 }).then((res) => {
    if (res && res.data) {
      specialMerchantOptions.value = res.data.map((item) => {
        return {
          label: item.nickName,
          value: item.userId
        }
      })
      specialMerchantOptions.value.unshift({
        label: '约饭派服务商-子账号',
        value: -1
      })
    } else {
      specialMerchantOptions.value = []
    }
  })
}
import { listDataApi } from '@/api/system/dict/data'
/** 获取结算周期 */
const getListData = () => {
  listDataApi({ dictType: 'settlement_cycle' }).then((res) => {
    if (res && res.rows) {
      freezeDayOptions.value = res.rows.map((item) => {
        return {
          label: item.dictLabel,
          value: Number(item.dictValue)
        }
      })
    }
  })
}

onMounted(() => {
  getRolelist()
})
/** 选中服务商(-1)的时候触发 服务商账号的请求 */
function change(e) {
  if (e && e === -1) {
    dialogFormModel.value.proceedsAccount = '1719406074'
  } else {
    dialogFormModel.value.proceedsAccount = ''
  }
}

/** 处理数据 */
function procList(type, index) {
  if (type === 'add') {
    if (dialogFormModel.value.positionSharings?.length < 10) {
      dialogFormModel.value.positionSharings.push({
        type: 3,
        userId: '',
        openId: '',
        accountNumber: '',
        freezeDay: '',
        proportion: ''
      })
    } else {
      ElMessage.warning('只能添加10个分账接收方')
    }
  } else if (type === 'delete') {
    dialogFormModel.value.positionSharings.splice(index, 1)
  }
}

/** 获取下拉框组件传回来item */
function getChange(row, val, option) {
  if (row && row.type === 3) {
    if (option.openId) {
      row.accountNumber = option.openId
    } else {
      row.accountNumber = ''
      ElMessage.warning('暂无UID，请用户先登录小程序')
    }
  } else if (row.type === 4) {
    row.accountNumber = serviceProvidersOptions[0].dictValue
  }
}
/**table Action */
function handleAdd() {
  handleTableAction({}, 'add')
}
function handleTableAction(obj, operType) {
  state.operType = operType
  if (operType == 'auth') {
    disablePoint({ id: obj.positionId, enabled: obj.enable }).then(() => {
      ElMessage.success('操作成功')

      getList()
    })
  } else {
    state.actionType = operType
    if (operType == 'detail') {
      state.detailId = obj.positionId
    } else if (operType == 'add') {
      if (!dialogFormModel.value.positionSharings.length && isAllPermissions.value) {
        dialogFormModel.value.positionSharings.push({
          type: 3,
          userId: '',
          openId: '',
          accountNumber: '',
          freezeDay: '',
          proportion: ''
        })
      }
      state.visible = true
    } else {
      console.log('编辑=======', obj)
      cityName.value = obj.areaName.split('/')[0]
      Object.keys(dialogFormModel.value).map((k) => {
        dialogFormModel.value[k] = obj?.[k]
      })
      // console.log('编辑', dialogFormModel.value)
      dialogFormModel.value.feeRate =
        dialogFormModel.value.feeRate && dialogFormModel.value.feeRate + '%'
      if (obj.positionSharings?.length && isAllPermissions.value) {
        dialogFormModel.value.positionSharings = deepClone(obj.positionSharings)
        dialogFormModel.value.positionSharings = dialogFormModel.value.positionSharings.map(
          (item) => {
            return {
              ...item,
              proportion: item.proportion + '%'
            }
          }
        )
      }
    }
    state.visible = true
  }
}

import { deepClone } from '@/utils'
import { nextTick } from 'vue'

/**dialog form */
function handleAction(confirm) {
  if (confirm) {
    let params = deepClone(dialogFormModel.value)
    // console.log(isAllPermissions.value)
    // console.log({ params })
    // // 判断用户是否是全部权限的
    // if (isAllPermissions.value) {
    // } else {
    //   params = {
    //     areaId: params.areaId,
    //     companyId: params.companyId,
    //     contracts: params.contracts,
    //     mobile: params.mobile,
    //     operationUserId: params.operationUserId,
    //     positionName: params.positionName,
    //     positionTypeId: params.positionTypeId,
    //     routeId: params.routeId
    //   }
    // }
    if (params.positionSharings?.length && isAllPermissions.value) {
      let sum = 0
      for (const item of params.positionSharings) {
        item.proportion = item.proportion && parseFloat(item.proportion.replace('%', ''))
        sum += Number(item.proportion)
        if (item && (!item.freezeDay || !item.accountNumber || !item.userId)) {
          return ElMessage.warning(
            !item.userId
              ? '收款人不能为空'
              : !item.accountNumber
              ? '收款账号不能为空'
              : !item.freezeDay
              ? '结算周期不能为空'
              : ''
          )
        }
      }
      if (Number(params.proportion) < sum)
        return ElMessage.warning('各个分账比例之和不可大于点位总分账比例')
    } else {
      params.positionSharings = []
    }
    params.feeRate = params.feeRate && parseFloat(params.feeRate.replace('%', ''))
    dialogFormRef.value?.validate((valid, callback) => {
      console.log(params)
      if (valid) {
        const isAdd = state.operType == 'add'
        handleUpdConfirm(isAdd, '确认要修改当前点位？').then(async () => {
          const fetchMethod = isAdd ? addPosition : updatePosition
          fetchMethod(params).then((r) => {
            ElMessage.success(isAdd ? '新增成功' : '更新成功')

            getList()
            state.visible = false
          })
        })
      }
    })
  } else {
    state.visible = false
  }
}

watch(
  () => state.visible,
  (v) => {
    if (!v) {
      nextTick(() => {
        dialogFormModel.value = {
          positionId: '',
          companyId: '',
          areaId: '',
          routeId: '',
          contracts: '',
          mobile: '',
          positionName: '',
          positionTypeId: '',
          proportion: '',
          feeRate: '',
          proceedsAccount: '',
          operationUserId: '',
          investorUserId: '',
          positionSharings: []
        }
      })
    } else {
      getListData()
    }
  }
)

/**init +  onActivated*/
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
.headName {
  width: 100%;
  display: flex;
  justify-content: space-between;
  ._name {
    flex: 1;
    text-align: center;
  }
}
._body {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
